package com.tiamo.traders.myinterceptor;


import com.alibaba.fastjson.JSONObject;
import com.tiamo.traders.entity.ResultModel;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;

/**
 * MVC的拦截器实现：拦截器的底层采用aop事项
 * 第一步：实现HandlerInterceptorAdapter类，完成拦截器的编写
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    /**
     * 接口方法的前置拦截
     * HttpServletRequest request：获取请求参数
     * HttpServletResponse response：相应数据的对象
     * <p>
     * 返回值：true-->执行目标函数（执行接口方法）
     * 返回值：false --> 接口方法不执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return super.preHandle(request, response, handler);
        /*String token = request.getHeader("token");
        System.out.println(token+"---------token--------");
        if(token != null && !token.equals("null") && token != ""){
            return true;
        } else {
            *//**
             * 在拦截器中需要设置跨域处理
             * *//*

            Writer writer = response.getWriter();
            writer.write(JSONObject.toJSONString(ResultModel.getResultModel(-1,"error")));
            //在拦截器中添加跨域处理：
            //Access-Control-Allow-Headers:允许前端带上任意自定义请求头
            //Access-Control-Allow-Origin:后端处理跨域问题。
            //跨域问题产生的情况：不同服务器之间的ajax访问都会产生跨域问题。
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "*");
            writer.close();
            return false;*/
        return true;


    }


//    /**接口方法的后置拦截*/
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        super.postHandle(request, response, handler, modelAndView);
//    }
//
//
//    /**异常拦截*/
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        super.afterCompletion(request, response, handler, ex);
//    }
}

